#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char* argv[]){
  int go= 1;
  FILE *outputfile;
  char command[28];
  char data[7];


  while (go=1)
  {
    sprintf(command, "sudo i2cget -y 1 0x49 0x00 w");
    sleep(1);
    int pf = popen(command, "r");

    if(!pf)
    {
      fprintf(stderr, "Could not open pipe for output.\n");
      return 0;
    }

    fgets(data, 7, pf);
    
    
    char subdata[5];
    memcpy(subdata, &data[2],4);
    subdata[4]='\0';
  
    char result[33];
    result[0] = '\0';
    int i = 0;
    while(subdata[i]){
	switch (subdata[i]){
	case '0':
	  strcat(result,"0000"); break;
	case '1':
	  strcat(result,"0001"); break;
	case '2':
	  strcat(result,"0010"); break;
	case '3':
	  strcat(result,"0011"); break;
	case '4':
	  strcat(result,"0100"); break;
	case '5':
	  strcat(result,"0101"); break;
	case '6':
	  strcat(result,"0110"); break;
	case '7':
	  strcat(result,"0111"); break;
	case '8':
	  strcat(result,"1000"); break;
	case '9':
	  strcat(result,"1001"); break;
	case 'a':
	  strcat(result,"1010"); break;
	case 'b':
	  strcat(result,"1011"); break;
	case 'c':
	  strcat(result,"1100"); break;
	case 'd':
	  strcat(result,"1101"); break;
	case 'e':
	  strcat(result,"1110"); break;
	case 'f':
	  strcat(result,"1111"); break;
	}
	i++;
      
      }

    float temperature = 0;

    for(int i=0;i<8;i++){
      switch (i){
	case 0:
	  if(result[i]=='1')
	    temperature+=1;
	  break;
        case 1:
	  if(result[i]=='1')
	    temperature+=0.5;
	  break;
        case 2:
	  if(result[i]=='1')
	    temperature+=0.25;
	  break;
      }
      
    }

    for(int i=15;i>7;i--){
      switch (i){
	case 15:
	  if(result[i]=='1')
	    temperature+=2;
	  break;
        case 14:
	  if(result[i]=='1')
	    temperature+=4;
	  break;
        case 13:
	  if(result[i]=='1')
	    temperature+=8;
	  break;
        case 12:
	  if(result[i]=='1')
	    temperature+=16;
	  break;
        case 11:
	  if(result[i]=='1')
	    temperature+=32;
	  break;
        case 10:
	  if(result[i]=='1')
	    temperature+=64;
	  break;
	case 9:
	  if(result[i]=='1')
	    temperature+=128;
	  break;
         case 8:
	  if(result[i]=='1')
	    temperature*=(-1);
	  break;
      }
      
    }
    /*
    outputfile = fopen("temperature.txt","w+");
    fprintf(outputfile, "%f\n", temperature);
    fclose(outputfile);
    */

    fprintf(stdout, "%f\n", temperature);
    fflush(stdout);

    

    if(pclose(pf)!=0)
      {
	fprintf(stderr, "Failed to close command stream \n");
      }
      }
  
  return 1;
  

}


